from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse, JsonResponse, FileResponse
from .models import Category, Theme, Book, Article, ThemeTwo
import random
from django.db.models import F
from django.views.decorators.http import require_POST
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

# Create your views here.

def index(request):
    cs = Category.objects.all()
    books = Book.objects.all()
    ts = Theme.objects.all()
    # books = random.sample(list(books), k=2)
    paginator = Paginator(books, 4)  # 每页显示4本书

    page = request.GET.get('page')
    try:
        books = paginator.page(page)
    except PageNotAnInteger:
        # 如果页码不是整数，则返回第一页
        books = paginator.page(1)
    except EmptyPage:
        # 如果页码超出范围，则返回最后一页
        books = paginator.page(paginator.num_pages)
    return render(request, "main/list.html", context={"books": books, "cs": cs, "ts": ts})


def category(request, c_id):
    cs = Category.objects.all()
    c = get_object_or_404(Category, id=c_id)
    ts = Theme.objects.all()
    tts = ThemeTwo.objects.all()
    books = c.book_set.all()
    paginator = Paginator(books, 4)  # 每页显示4本书

    page = request.GET.get('page')
    try:
        books = paginator.page(page)
    except PageNotAnInteger:
        # 如果页码不是整数，则返回第一页
        books = paginator.page(1)
    except EmptyPage:
        # 如果页码超出范围，则返回最后一页
        books = paginator.page(paginator.num_pages)
    return render(request, 'main/list.html', locals())


def theme(request, c_id, t_id):
    # cs = Category.objects.all()
    c = get_object_or_404(Category, id=c_id)
    ts = Theme.objects.all()
    tts = ThemeTwo.objects.all()

    if c_id==1:
        t = get_object_or_404(Theme, id=t_id)
        books = Book.objects.filter(category=c, theme=t)
        paginator = Paginator(books, 4)  # 每页显示4本书

        page = request.GET.get('page')
        try:
            books = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是整数，则返回第一页
            books = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围，则返回最后一页
            books = paginator.page(paginator.num_pages)
        # return render(request, 'main/list.html', locals())
    if c_id == 2:
        t = get_object_or_404(ThemeTwo, id=t_id)
        if t_id == 1:
            books = Book.objects.filter( views__gt=10).order_by('-views')
        if t_id == 2:
            books = Book.objects.filter( favorite_count__gt=10).order_by('-favorite_count')


    if c_id == 1:
        return render(request, 'main/list.html', locals())
    elif c_id == 2:
        return render(request, 'main/top.html', locals())


def detail(request, book_id):
    book = get_object_or_404(Book, id=book_id)
    ats = Article.objects.all()
    # books = Book.objects.filter(category=c, theme=t)
    author_name = book.auther
    description = book.description
    chapter_numbers = {}
    last_book_title = None
    chapter_number = 0
    for at in ats:
        if at.book.title != last_book_title:
            chapter_number = 1
            last_book_title = at.book.title
        else:
            chapter_number += 1
        chapter_numbers[at.id] = chapter_number
    return render(request, 'main/detail.html', locals())


def article(request, book_id, at_id):
    book = get_object_or_404(Book, id=book_id)
    ats = Article.objects.all()
    at = get_object_or_404(Article, id=at_id)

    return render(request, 'main/text.html', locals())


def download(request, book_id):
    book = get_object_or_404(Book, id=book_id)
    book.views += 1
    book.save()
    return FileResponse(book.image, as_attachment=True, filename=book.image.name)


@require_POST
def favorite(request, book_id):
    book = get_object_or_404(Book, pk=book_id)
    is_favorite = request.POST.get('is_favorite', 'false') == 'true'

    if is_favorite:
        book.favorite_count += 1
    else:
        book.favorite_count = max(book.favorite_count - 1, 0)

    book.save()

    return JsonResponse({
        'favorite_count': book.favorite_count,
        'is_favorite': is_favorite
    })
